$(function(){
    $("#msgbar").click(function(){
        $(this).fadeOut(); 
		
		clearTimeout($(this).data('timer'));
    });
})

/**
 * Replaces all occurrences of 'findWhat' with 'replaceWith' in 'this'
 * 
 * @param string findWhat the string containing what to find in the source string
 * @param string replaceWith the string which will replace all occurrences of replaceWhat
 * 
 * @return string the replaceWhere string with all the occurrences replaced
 */
String.prototype.replaceAll = 
	function (findWhat, replaceWith) 
	{
		//return this.replace(new RegExp(findWhat, "g"), replaceWith);
		
		str = this;
		
		while (str.indexOf(findWhat) >= 0)
			str = str.replace(findWhat, replaceWith);
		
		return str;         
		
	};  
	
// Gets the json object from the specified url
// shows the .message string and
// if .success is set to true calls the callback function
function jsonData(url, success)
{
	$("#loading").fadeIn();
	
	$.getJSON(url,
		function (data)
		{
			showCustomMsg(data.message);
			
			if (data.success)
				success();
			
			$("#loading").fadeOut();
		});
}

/**
 * Just like the built in escape function
 * but treats some other characters as unsafe 
 * 
 * @param string s the string to be escaped
 * @return string the string with the characters escaped
 */
function escapestr(s)                      
{
	return escape(s).replaceAll('+', '%2B').replaceAll("'", '%27').replaceAll('\\', '%5C');
}

/**
 * Toggles the panel's visibility with id as in the argument
 */
function togglePanel(id)
{   
	anchor = document.getElementById("anchor_" + id);
	
	if (anchor)
	{ 
		if (anchor.innerHTML == "( + )")
		{             
			$("#fspan" + id).fadeIn(200);
			anchor.innerHTML = "( - )";   
		}
		else
		{           
			anchor.innerHTML = "( + )";
			$("#fspan" + id).fadeOut(200);
		}
	}
}

/**
 * Sets upload form status
 */
function setUpStatus(s)                   
{
	$("#upResult").html(s);
}

/**
 * called when a the upload form is submitted
 */
function startUpload()
{
	// Validating if the upload form has some file selected
	if (document.forms.f.file.value.length == 0)
	{
		alert('No file selected');
		
		return false;
	}
	
	setUpStatus('uploading ...');
	 
	return true;
}

/**
 * called by upload.php when an upload is finished
 */
function finishUpload(result)
{           
    setUpStatus(result);    
}

/**
 * closes the upload form
 */
function closeUploadForm()
{
	$("#upform").slideUp();
	$("#upform").data('isVisible', "0");
}    

function showMsgDiv()
{
	$("#msgdiv").hide();
	$("#msgdiv").slideDown(200);
}

/**
 * Hides the message div in explorer 
 */
function hideMsgDiv()
{
	$("#msgdiv").text("");  
	$("#msgdiv").slideUp(100);
}

function showCustomMsg(msg)
{
	var msgbar = $("#msgbar");

	clearTimeout(msgbar.data('timer'));

    msgbar
        .html(msg)
        .fadeIn();
        
    msgbar.data('timer', setTimeout("$('#msgbar').fadeOut();", 5000));    
}

/**
 * Shows a message to the 'msgdiv' element from an ajax.get request
 */
function msgFromRequest(url, postparams, isPost)
{
	var load_img = $("#loading");
	
	load_img.fadeIn();
	
	$.ajax({
		'url': url,
		'method': (isPost ? 'POST' : 'GET'),
		'data': (postparams ? postparams : ''),
		'success': function(e){
			showCustomMsg(e);
			load_img.fadeOut();
		},
		'error': function(e){
			showCustomMsg(e);
			load_img.fadeOut();
		}
	});
	
	
//	showMsgDiv();
//	
//	if (isPost)
//		ajax.htmlFromPostRequest
//		(
//			'msgdiv', 
//			url, 
//			postparams, 
//			'&nbsp;<a class="nounderline" href="javascript:hideMsgDiv()">[ Hide message ]</a>'
//		);
//	else
//		ajax.htmlFromRequest
//		(
//			'msgdiv', 
//			url, 
//			'&nbsp;<a class="nounderline" href="javascript:hideMsgDiv()">[ Hide message ]</a>'
//		);            
}

/**
 * Prompts the user to enter a path and calls the aproporiate file
 * to create it
 */
function promptmkdir(basedir)
{
	s = prompt("Enter the directory name you want to create");
	
	if (s == null)
		return;
		
	jsonData('manager.php?action=mkdir&p=' + escape(basedir + '/' + s),
		function ()
		{
			$("#main-tbl").append("<tr class='new'><td>&nbsp;<img src='img/new.png'>&nbsp;" + s + 
				"</td><td>new directory</td></td>&nbsp;</tr>");
		});
}

/**
 * Prompts the user to delete or not the directory passed as argument
 */
function rmdir(dir, rowNr)
{
	if (!confirm("Are you sure you want to delete the selected directory ?"))
		return;
	
	url = "";
		
	if (confirm("Do you want to delete subfolders and their files? WARNING: If you choose to delete them this cannot be undone"))
		url = "manager.php?action=rmdir&subs=1&p=" + dir;
	else
		url = "manager.php?action=rmdir&subs=0&p=" + dir;
		
		
	jsonData(url, 
		function ()
		{
			$("#row"+rowNr).remove();
		}
		);
}

/**
 * Deletes a file
 */
function rmfile(file, rowNr)
{
	if (confirm("Are you sure you want to delete this file ?"))
	{
		jsonData('manager.php?action=rmfile&f=' + file,
			function ()
			{ 
				$("#row"+rowNr).remove();
			});
	}    
}

function savefile()
{   
	document.editor.submit();
}

function mkfile(basedir)
{
	s = prompt("Enter filename (name + ext)");
	
	if ( s == null)
		return;
		
	jsonData('manager.php?action=mkfile&f=' + escapestr(basedir + '/' + s),
		function ()
		{
			$("#main-tbl").append("<tr class='new'><td>&nbsp;<img src='img/new.png'>&nbsp;" + s + 
			"</td><td>new file</td></td>&nbsp;</tr>");
		});
}

/**
 * refreshes the page and keeps the uploader open or not 
 * depending on it's state at the moment of refresh
 */
function pageRefresh(includeMask)
{
	currDir = $("#currdir").val();
	mask = $("#searchbox").val();
	uploader = $("#upform").data('isVisible') == '1' ? 1 : 0;
	
	mask = ((includeMask) && (mask.length > 0)) ? "&mask=" + escape(mask) : "";
	
	window.location = "?v=" + currDir + mask + "&openuploader=" + uploader;
}

function logout()
{
	if (confirm('Are you sure you want to log out?'))
		window.location="login.php?logout";
}


/**
* Returns a string containing the checked file names
*/
function getCheckedFiles()
{
	result = "";

	// get all checkboxes in the document
	checks = $("#main-tbl input:checkbox");
	
	for (i=0; i < checks.length; i++)
	{
		// If a  checkbox is checked
		// then add it's value to the result
		// files are separated by a star character
		if (checks.get(i).checked)
			result += (checks.get(i).value + ( (i+1 == checks.length) ? "" : "*"));
	}
	
	return result;
}

function checkAll(doCheck)
{
	checks = $("input:checkbox");
	
	for (i=0; i<checks.length; i++)
		checks.get(i).checked = doCheck;
}

function invertSelection()
{
	checks = $("input:checkbox");
	
	for (i=0; i<checks.length; i++)
		checks.get(i).checked = !checks.get(i).checked;
}



/**
 * Downloads the checked files
 */
function downloadChecked()
{
	checked = getCheckedFiles();
	
	if (checked.length == 0)
	{
		showCustomMsg('No files selected');
		return;
	}
		
	window.location='manager.php?action=dlthis&f=' + checked;
}

/**
 * Deletes the checked files
 */

function deleteCheckedFiles()
{
	checked = getCheckedFiles();
	
	if (checked.length == 0)
	{
		showCustomMsg('No files selected');
		return;
	}
	
	jsonData('manager.php?action=delthis&f=' + checked,
		function ()
		{
			// .parent is the span, .parent.parent is the table row
			$(":checked").parent().parent().remove();
		});
}

function cut()
{
	checked = getCheckedFiles();
	
	if (checked.length == 0)
	{
		showCustomMsg('No files selected');
		return;
	}
		
	msgFromRequest('manager.php?action=cut&f=' + checked);
}

function copy()
{
	checked = getCheckedFiles();
	
	if (checked.length == 0)
	{
		showCustomMsg('No files selected');
		return;
	}
		
	msgFromRequest('manager.php?action=copy&f=' + checked);
}


function paste(dir)
{      
	showCustomMsg('Checking files ...');
	
	// Sending a request to know if any
	// file will need to be overwritten
	ajax.get('manager.php?action=checkovr&p=' + dir,
		function (result)
		{
			if (result)
			{
				// Manager.php will output either string "true" or
				// string "false"
				// "true" in case overwrite is necessary
				
				// If there is an overwrite needed
				// show a message to the user
				// and let him decide
				
				if (result == "true")
				{
					href_ovr = "javascript:msgFromRequest('manager.php?action=paste&ovr=1&p=" + dir + "')";   
					href_no_ovr = "javascript:msgFromRequest('manager.php?action=paste&ovr=0&p=" + dir + "')"; 
					msg = "Some files already exist in the target directory. Overwrite them? ";
					
					showCustomMsg(msg + "[<b><a href=" + href_ovr + ">Yes</a>, " +
						"<a href=" + href_no_ovr + ">No</a>, " +
						"<a href='javascript:hideMsgDiv();'>Abort</a></b>]");
				}
				else
				if (result == "false")
				{
					// proceed with pasting
					msgFromRequest('manager.php?action=paste&p=' + dir); 
					return;
				}  
				else
					// In case the message is something different
					// just show it
					showCustomMsg(result);
					
			}
			else
				showCustomMsg('Unable to complete request');
		}
	)
}

function dlDir(dir)
{
	showCustomMsg('Please wait while preparing zip archive. This might take a while.');
	window.location='manager.php?action=dldir&p=' + dir;
}

function renameFile(encoded, actualfn)
{
	newfn = prompt("Enter new filename", actualfn);
	
	if (newfn.length == 0)
	{
		showCustomMsg('New filename cannot be empty');
		return;
	}

	msgFromRequest('manager.php?action=renameFile&f=' + encoded + "&rento=" + escapestr(newfn));
}
